package org.example.service;

import jakarta.annotation.Resource;
import org.example.entity.MyUser;
import org.example.mapper.UserMapper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;


@Service
public class MyUserDetailsService implements UserDetailsManager, UserDetailsPasswordService {


    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        MyUser myUser = userMapper.getUserByName(username);

        if(myUser == null){
            throw new UsernameNotFoundException(username);
        }


        UserDetails userDetails = User.builder()
                .username(myUser.getName())
                //实现了UserDetailsPasswordService，{noop}就不能在加入了，否则会报错
//                .password("{noop}"+myUser.getPassword())
                .password(myUser.getPassword())
                .roles("USER")
                .build();

        return userDetails;
    }

    @Override
    public void createUser(UserDetails user) {
        MyUser myUser = MyUser.builder()
                .name(user.getUsername())
                .password(user.getPassword())
                .build();
        userMapper.insertUser(myUser);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }


    //修改密码,在用户登录完成之后，修改数据库的密码
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        int i = userMapper.upgradePassword(user.getUsername(), newPassword);
        return user;
    }
}
